<?php
class XTableTraverser{
	protected $query = array();
	protected $tables = array();
	
	public function __construct(XQuery $query, array $tables){
		$this->query = $query;
		$this->tables = $tables;
	}
	
	public function traverse($offset = 0, $size = 0, $asArray = false){
		if(is_null($offset) || $offset <= 0){
			$offset = 0;
		}
		if(is_null($size) || $size <= 0){
			$results = array();
			foreach($this->tables as $table){
				$results = array_merge($results, $this->query
					->cloneQuery()
					->table($table)
					->findAll($asArray));
			}
			return $results;			
		}
		$total = 0;
		$fetch = false;
		$results = array();
		foreach($this->tables as $table){
			$count = $this->query->cloneQuery()
				->table($table)
				->count();
			if($fetch){
				$results = array_merge($results, $this->query->cloneQuery()
					->size($size - count($results))
					->table($table)
					->findAll());
				if(count($results) >= $size){
					return $results;
				}
				$total += $count;			
				continue;
			}
			if($total <= $offset && $total + $count > $offset){
				$fetch = true;
				$results = $this->query->cloneQuery()
					->offset($offset - $total)
					->size($size)
					->table($table)
					->findAll();
				if(count($results) >= $size){
					return $results;
				}
				$total += $count;			
				continue;
			}
			$total += $count;
		}
		return $results;
	}
	
	public function aggregate($aggregate, $field){
		$total = 0;
		foreach($this->tables as $table){	
			$total += $this->query->cloneQuery()
				->table($table)
				->$aggregate($field);
		}
		return $total;		
	}
	
}
?>